#!C:\Python25\python.exe

import SyntaxParser
import SQLGenerator2
import conn
import condition
import answer
import patientCondition
import statistic
import Result
import Results
import cgi
import Diagnosis
from DatabaseConnector import leaves
import template_parser
import result_parser
import notesretrieve
import reportoutput
import ConfigParser
import notes_parser

cfg = ConfigParser.ConfigParser()
cfg.read("path.cfg")
templatepath = cfg.get("template", "path")
reportpath = cfg.get("report", "path")
resultpath = cfg.get("result", "path")

print "Content-Type: text/html\n\n"

#Handover report output
if reportoutput.form.getvalue("template") is None:
   reportoutput.xml2output()
else:      
   # --------- dictionaries for archival database -----------
   
   path = 'doc/archive_patientevents_dictionary.txt'
   archive_patientevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/archive_chartevents_dictionary.txt'
   archive_chartevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/archive_medevents_dictionary.txt'
   archive_medevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/archive_labevents_dictionary.txt'
   archive_labevents_dictionary = SyntaxParser.buildHash(path)
   
   # --------- dictionaries for realtime database -----------
   
   path = 'doc/realtime_patientevents_dictionary.txt'
   realtime_patientevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/realtime_chartevents_dictionary.txt'
   realtime_chartevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/realtime_categoric_terms.txt'
   categoric_terms = SyntaxParser.buildCategoricArray(path)
   
   path = 'doc/realtime_medevents_dictionary.txt'
   realtime_medevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/realtime_labevents_dictionary.txt'
   realtime_labevents_dictionary = SyntaxParser.buildHash(path)

   #added by Thomas Xie 23,May, 2008
   path = 'doc/realtime_adtevents_dictionary.txt'
   realtime_adtevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/realtime_drugevents_dictionary.txt'
   realtime_drugevents_dictionary = SyntaxParser.buildHash(path)
   
   # --------- dictionaries shared by both databases -----------
   
   path = 'doc/groupevents_dictionary.txt'
   groupevents_dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/interface/dictionary.txt'
   dictionary = SyntaxParser.buildHash(path)
   
   path = 'doc/interface/patient_attributes.txt'
   patient_attributes = SyntaxParser.buildHash(path)
   
   path = 'doc/interface/toc_list.txt'
   toc_array = SyntaxParser.buildArray(path)
   
   path = 'doc/interface/databases.txt'
   standard_databases = SyntaxParser.buildArray(path)
   
   path = 'doc/interface/ref_entities.txt'
   reference_entities = SyntaxParser.buildArray(path)
   
   path = 'doc/interface/sta_entities.txt'
   stat_entities = SyntaxParser.buildArray(path)
   
   path = 'doc/interface/med_entities.txt'
   medical_entities = SyntaxParser.buildHash(path)
   #------------------------------------------------
   comparands = [">",">=","<","<=","=","<>"]
   types = ["and", "or"]
   ref_fns = ["all values", "any value", "last value"] # yet to implement last value
   stat_fns = ["mean", "sd", "median", "max", "min", "range", "mode", "sum", "count"] # yet to implement sum and count
   time_entities = ["hours", "days", "weeks"]
   keywords = [" whose ", " with ", " have ", " during ", " in "]
   
   #-------------------------------------------------
   
   template = str(reportoutput.form.getvalue("template"))
   templatefilename = templatepath + template + ".xml"
   mrn = str(reportoutput.form.getvalue("MRN"))
#   
   templateparser = template_parser.template_parser(templatefilename)
   
   patient = templateparser.get_patient(mrn)
   cond = templateparser.get_cond()
   toc = templateparser.get_toc()
   db = templateparser.get_db()
   diagnosis = templateparser.get_diagnosis()
   time_val = templateparser.get_time_value()
   time_ent = templateparser.get_time_ent()
   ward = templateparser.get_ward()
   answer = templateparser.get_answer()
   
     
   duration = SyntaxParser.toHours(time_val, time_ent)
   if duration > 48:
      real_time_val = 48 # use in realtime
   else:
      real_time_val = time_val
             
   results = Results.Results([],[],[])
   
   
   # Obtain the group-events component of the answer, if any (such as sedation, inotropes, etc)
   groupevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, groupevents_dictionary)
   
   # Obtain the chart-events component of the answer, if any (such as HR, Vent Mode, etc)
   chartevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_chartevents_dictionary)
   
   # Obtain the patient-events component of the answer, if any (such as mrn, fullname, etc)
   patientevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_patientevents_dictionary)
   
   # Obtain the med-events component of the answer, if any (such as any sedation and inotrope, etc)
   medevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_medevents_dictionary)
   
   # Obtain the lab-events component of the answer, if any (such as calcium, etc)
   labevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_labevents_dictionary)

   # Obtain the adt-events component of the answer, if any (such as admit time, bed number etc)
   adtevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_adtevents_dictionary)
   
   drugevents_answers = SyntaxParser.getAnswers(answer, ref_fns, stat_fns, realtime_drugevents_dictionary)
   
   # Obtain the patient-events component of the conditions for the archival database, if any (such as mrn, fullname, etc)
   patient_conditions = SyntaxParser.getConditions(patient, comparands, types, realtime_patientevents_dictionary, 'T')
   patientevents_conditions = SyntaxParser.transform_Conditions(patient_conditions, "realtime")

   # Obtain the adt-events component of the conditions for the realtime database, if any (such as admit time,bed No.
   adtevents_conditions = SyntaxParser.getConditionArray(cond, comparands, types, realtime_adtevents_dictionary)

   # Obtain the chart-events component of the conditions, if any (such as HR, Vent Mode, etc)
   chartevents_conditions = SyntaxParser.getConditionArray(cond, comparands, types, realtime_chartevents_dictionary)
   
   # Obtain the med-events component of the conditions, if any (such as any sedation and inotrope, etc)
   medevents_conditions = SyntaxParser.getConditionArray(cond, comparands, types, realtime_medevents_dictionary)
   
   # Obtain the lab-events component of the conditions, if any (such as calcium, etc)
   labevents_conditions = SyntaxParser.getConditionArray(cond, comparands, types, realtime_labevents_dictionary)
   
   SQL = SQLGenerator2.SQLGenerator2('SNOMED','GICU',groupevents_answers,patientevents_answers,adtevents_answers,
                                   chartevents_answers,medevents_answers,labevents_answers, 
                                   patientevents_conditions,adtevents_conditions,chartevents_conditions,medevents_conditions, 
                                   labevents_conditions, None, real_time_val, time_ent, ward, categoric_terms)
   
   resultsArray = [] # array of results
   logicalArray = [] # array of logical operator
   result_set = [] # final set of results
   
   patients = None
   
   #append patients satisfying demographic info to the results array
   if patient_conditions is not None:
       patientQuery = SQL.getPatientEvent()
       patients = conn.toGICU(patientQuery)

   for condition in adtevents_conditions:
       logicalArray.append(condition.getType())
       subQuery = SQL.generateSingleQuery(condition, "adtevents")
       res = conn.toGICU(subQuery)
       resultsArray.append(res)
   
   for condition in chartevents_conditions:
       logicalArray.append(condition.getType())
       subQuery = SQL.generateSingleQuery(condition, "chartevents")
       res = conn.toGICU(subQuery)
       resultsArray.append(res)
   
   for condition in medevents_conditions:
       logicalArray.append(condition.getType())
       subQuery = SQL.generateSingleQuery(condition, "medevents")
       res = conn.toGICU(subQuery)
       resultsArray.append(res)
   
   for condition in labevents_conditions:
       logicalArray.append(condition.getType())
       subQuery = SQL.generateSingleQuery(condition, "labevents")
       res = conn.toGICU(subQuery)
       resultsArray.append(res)
   
   # Get the final group of patients whose conditions are satisfied
   finalResultArray = SyntaxParser.getFinalResult(patients, resultsArray, logicalArray)
   
   cont = 1
   if finalResultArray is None:
      # if none, then there is no conditions, so retrieve all records in db
      cont = 1
      
   elif len(finalResultArray) == 0:
      # if length = 0, then there is no patient that satisfy all condition,s so retur nothing
      cont = -1
   
   if cont == 1:
      for ind in range(0,len(groupevents_answers)):
          query_realtime = SQL.generateFinalQuery("groupevents", finalResultArray, ind)
          #print query_realtime
          res_realtime = conn.toGICU(query_realtime,4)
      
          # creating a Result Object
          result = Result.Result(groupevents_answers[ind].getVariable(),"groupevents",res_realtime,groupevents_answers[ind].getStat_fn(),groupevents_answers[ind].getRef_fn())
      
          # Append Result object to Results
          results.AppendRealtime(result)
      
      for ind in range(0,len(patientevents_answers)):
          query_realtime = SQL.generateFinalQuery("patientevents", finalResultArray, ind)
                         #print query_realtime
          res_realtime = conn.toGICU(query_realtime)
      
          # creating a Result Object
          result = Result.Result(patientevents_answers[ind].getVariable(),"patientevents",res_realtime,patientevents_answers[ind].getStat_fn(),patientevents_answers[ind].getRef_fn())
      
          # Append Result object to Results
          results.AppendRealtime(result)

      for ind in range(0,len(adtevents_answers)):
           query_realtime = SQL.generateFinalQuery("adtevents", finalResultArray, ind)
           print query_realtime
           res_realtime = conn.toGICU(query_realtime)
	
	    # creating a Result Object
           result = Result.Result(adtevents_answers[ind].getVariable(),"adtevents",res_realtime,adtevents_answers[ind].getStat_fn(),adtevents_answers[ind].getRef_fn())
	
	    # Append Result object to Results
           results.AppendRealtime(result)	
      
      for ind in range(0,len(chartevents_answers)):
          query_realtime = SQL.generateFinalQuery("chartevents", finalResultArray, ind)
                         #print query_realtime
          res_realtime = conn.toGICU(query_realtime,3)
      
          # creating a Result Object
          result = Result.Result(chartevents_answers[ind].getVariable(),"chartevents",res_realtime,chartevents_answers[ind].getStat_fn(),chartevents_answers[ind].getRef_fn())
      
          # Append Result object to Results
          results.AppendRealtime(result)
      
      for ind in range(0,len(medevents_answers)):
          query_realtime = SQL.generateFinalQuery("medevents", finalResultArray, ind)
                         #print query_realtime
          res_realtime = conn.toGICU(query_realtime,3)
      
          # creating a Result Object
          result = Result.Result(medevents_answers[ind].getVariable(),"medevents",res_realtime,medevents_answers[ind].getStat_fn(),medevents_answers[ind].getRef_fn())
      
          # Append Result object to Results
          results.AppendRealtime(result)
      
      for ind in range(0,len(labevents_answers)):
          query_realtime = SQL.generateFinalQuery("labevents", finalResultArray, ind)
                         #print query_realtime
          res_realtime = conn.toGICU(query_realtime,3)
          
          # creating a Result Object
          result = Result.Result(labevents_answers[ind].getVariable(),"labevents",res_realtime,labevents_answers[ind].getStat_fn(),labevents_answers[ind].getRef_fn())
      
          # Append Result object to Results
          results.AppendRealtime(result)    
      
      results.setFinalResult(results.getRealtimeResult())
      #CDAL query Result
      final_result = results.getFinalResult()
   
##   print "start"
##   print len(final_result)
##   for res in final_result:
##      print "once"
##      values = res.getValues()
##      for rs in values:         
##         print "value = " + str(rs)
##
##   for i in range(len(final_result)):
##      print i
##      values = final_result[i].getValues()
##      for j in range(len(values)):
##         print j
##         print "value = " + str(values[j])

   
   #Notes retrieve result and notes parser
   notes = notesretrieve.notes_retrieve(94711) #94711
   np = notes_parser.notes_parser(notes)   
   #initial = np.parse("initial")
   
   #report out
   print "Content-Type: text/html\n\n"
   reportoutput.template2output(templatefilename, final_result, np,)

